#include "Canvas.h"

Canvas::Canvas(QWidget *parent) : buffer(560, 560) {
    setFixedSize(560, 560);
    setParent(parent);
    onDrawing = false;
    setGeometry(10, 10, 560, 560);
    setStyleSheet("background-color:rgb(0,0,0);");
    pen.setColor(QColor(255, 255, 255));
    pen.setWidth(30);
    pen.setJoinStyle(Qt::RoundJoin);
    pen.setCapStyle(Qt::RoundCap);
}

void Canvas::paintEvent(QPaintEvent *) {
    if(onDrawing)
        temp.drawLine(prev, current);
    painter.begin(this);
    painter.setRenderHint(QPainter::Antialiasing);
    painter.setPen(pen);
    painter.drawPixmap(rect(), buffer);
    painter.end();
}

void Canvas::mouseMoveEvent(QMouseEvent *event) {
    if (onDrawing) {
        current = event->pos();
        repaint();
        prev = current;
    }
    return QWidget::mouseMoveEvent(event);
}

void Canvas::mousePressEvent(QMouseEvent *event) {
    if (event->button() == Qt::LeftButton) {
        temp.begin(&buffer);
        temp.setPen(pen);
        temp.setRenderHint(QPainter::Antialiasing);
        onDrawing = true;
        prev = current = event->pos();
        update();
    }
    return QWidget::mousePressEvent(event);
}

void Canvas::mouseReleaseEvent(QMouseEvent *event) {
    if (event->button() == Qt::LeftButton) {
        update();
        temp.end();
        onDrawing = false;
    }
    return QWidget::mousePressEvent(event);
}

void Canvas::clear() {
    buffer.fill(Qt::black);
    update();
}